package com.jyxd.web.util;

import com.google.common.base.CaseFormat;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.util.*;

public class ObjectUtil {

    public static <T> List<T> castList(Object obj, Class<T> clazz) {
        List<T> result = new ArrayList<T>();
        if (obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                result.add(clazz.cast(o));
            }
            return result;
        }
        return null;
    }

    /**
     * Object转Map
     *
     * @param
     * @return
     */
    public static Map<String, Object> getObjectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<String, Object>();
        Class<?> cla = obj.getClass();
        Field[] fields = cla.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String keyName = field.getName();
            Object value = field.get(obj);
            if (value == null)
                value = "";
            map.put(keyName, value);
        }
        return map;
    }

    public static <V> List<Map<String,V>> objConvertListMap(Object obj, Class<V> vClass) throws IllegalAccessException {
        List<Map<String, V>> result = new ArrayList<>();
        if (obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                Map<String, V> map = new HashMap<>(16);
                Class<?> oClass = o.getClass();
                for (Field field : oClass.getDeclaredFields()) {
                    field.setAccessible(true);
                    String key = field.getName();
                    Object value = field.get(key);
                    if (value == null) {
                        value = "";
                    }
                    map.put(key, vClass.cast(value));
                }
                result.add(map);
            }
            return result;
        }
        return null;
    }

    /**
     * 判断数据是否为空
     *
     * @param object
     * @return
     */
    public static boolean objectStrIsNull(Object object) {
        if (Objects.isNull(object)) {
            return true;
        }
        if (StringUtils.isEmpty(String.valueOf(object))) {
            return true;
        }
        return false;
    }

    /**
     * 小写驼峰命名改为下划线
     *
     * @param name
     * @return
     */
    public static String humpToUnderline(String name) {
        if (name.contains("ID")) {
            name = name.replace("D", "d");
        }
        if (name.contains("OBR")) {
            name = name.replace("OBR", "Obr");
        }
        if (name.contains("OBX")) {
            name = name.replace("OBX", "Obx");
        }
        if (name.contains("PID")) {
            name = name.replace("PID", "Pid");
        }
        return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, name);
    }
}
